package com.cap.dreamcircle.View;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Model.Action.KeyCounterAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.RecordAudioEntity;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.AudioRecoderUtils;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.KeyCounterUtils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.RetrofitUploadFileParameterBuilder;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qssq666.voiceutil.record.MediaType;
import cn.qssq666.voiceutil.record.RecordFactory;
import cn.qssq666.voiceutil.record.RecordManagerI;
import cn.qssq666.voiceutil.utils.MediaDirectoryUtils;
import de.greenrobot.event.EventBus;
import okhttp3.RequestBody;
import rx.functions.Action0;

/**
 * 梦境记录主题选择画面
 * Created by liucxu on 2017/8/1.
 */

public class RecordDreamTitleActivcity extends BaseActivity {
    @BindView(R.id.imv_good_dreams)
    ImageView imv_good_dreams;
    @BindView(R.id.imv_bad_dreams)
    ImageView imv_bad_dreams;
    @BindView(R.id.imv_normal_dreams)
    ImageView imv_normal_dreams;
    @BindView(R.id.layout_center_title)
    LinearLayout layout_center_title;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.layout_back)
    LinearLayout layout_back;

    @BindView(R.id.imv_voice)
    ImageView imv_voice;
    @BindView(R.id.edt_dream_desc)
    EditText edt_dream_desc;
    @BindView(R.id.view_title_horizontal_line)
    View view_title_horizontal_line;

    @BindView(R.id.layout_stop_record_voice)
    RelativeLayout layout_stop_record_voice;
    @BindView(R.id.imv_bg_stop_record_voice)
    ImageView imv_bg_stop_record_voice;
    @BindView(R.id.imv_bg_stop_record_voice_front)
    ImageView imv_bg_stop_record_voice_front;
    @BindView(R.id.imv_stop_record_voice)
    ImageView imv_stop_record_voice;

    @BindView(R.id.layout_voice_wma_first)
    RelativeLayout layout_voice_wma_first;
    @BindView(R.id.imv_playing_status_audio1)
    ImageView imv_playing_status_audio1;
    @BindView(R.id.tv_length_audio1)
    TextView tv_length_audio1;

    @BindView(R.id.layout_voice_wma_second)
    RelativeLayout layout_voice_wma_second;
    @BindView(R.id.imv_playing_status_audio2)
    ImageView imv_playing_status_audio2;
    @BindView(R.id.tv_length_audio2)
    TextView tv_length_audio2;

    @BindView(R.id.layout_voice_wma_third)
    RelativeLayout layout_voice_wma_third;
    @BindView(R.id.imv_playing_status_audio3)
    ImageView imv_playing_status_audio3;
    @BindView(R.id.tv_length_audio3)
    TextView tv_length_audio3;

    @BindView(R.id.tv_complete)
    TextView tv_complete;

    private ValueAnimator animation_good_dreams;
    private ValueAnimator wave_animator;
    private int dream_type = 0;
    private List<RecordAudioEntity> audio_entities = new ArrayList<>();

    private AudioRecoderUtils audioRecorder;
    private MediaPlayer player;
    private boolean is_audio1_pause = false;

    private IDreamModel model;

    private View notice_confirm_view;
    private Dialog notice_confirm_dialog;

    private CheckBox radio_btn;
    private TextView tv_publish_cancel;
    private TextView tv_publish_confirm;
    private CheckBox radio_btn_anonymous;


    MediaType mediaType = MediaType.MP3;
    private RecordManagerI recordManager;
    private File mAudioFile;
    private String dreamTime="";

    @Override
    public int getLayoutId() {
        return R.layout.activity_record_dream_title;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        notice_confirm_view = View.inflate(RecordDreamTitleActivcity.this, R.layout.dialog_confirm_save, null);
        initDialoigViews();
        initBindDialog();
        tv_title.setText("");
        tv_complete.setEnabled(false);
        view_title_horizontal_line.setVisibility(View.GONE);
        wave_animator = ValueAnimator.ofFloat(0, 1).setDuration(2000);
        wave_animator.setRepeatMode(ValueAnimator.RESTART);
        wave_animator.setRepeatCount(ValueAnimator.INFINITE);
        wave_animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                imv_bg_stop_record_voice.setScaleX(1f + (1.4f) * percent);
                imv_bg_stop_record_voice.setScaleY(1f + (1.4f) * percent);
                imv_bg_stop_record_voice.setAlpha(0.8f - 0.8f * percent);
                if (percent > 0.5) {
                    imv_bg_stop_record_voice_front.setScaleX(1 + 1.2f * (percent - 0.5f));
                    imv_bg_stop_record_voice_front.setScaleY(1 + 1.2f * (percent - 0.5f));
                    imv_bg_stop_record_voice_front.setAlpha(0.8f - 0.8f * percent);
                }
            }
        });
        //初始化录音工具类
        audioRecorder = new AudioRecoderUtils();
        audioRecorder.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
                audio_entities.get(audio_entities.size() - 1).setLength((int) time);
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
//                Logger.i("录音保存在：" + filePath);
                tv_complete.setEnabled(true);
                tv_complete.setTextColor(Color.parseColor("#ffffff"));
                audio_entities.get(audio_entities.size() - 1).setAudioPath(filePath);
                showRecordAudioAnimation();
            }
        });
        player = new MediaPlayer();
//        try {
//            player.setDataSource("/storage/emulated/0/dream_circle_record/1501659039.amr");
//            player.prepare();
//            player.start();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        edt_dream_desc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    if (audio_entities.size() == 0) {
                        tv_complete.setEnabled(false);
                        tv_complete.setTextColor(Color.parseColor("#58626e"));
                    }
                } else {
                    tv_complete.setEnabled(true);
                    tv_complete.setTextColor(Color.parseColor("#ffffff"));
                }
            }
        });


        boolean mkdirs = MediaDirectoryUtils.getCachePath().mkdirs();
        MediaDirectoryUtils.setMediaManagerProvider(new MediaDirectoryUtils.MediaManagerProvider() {
            @Override
            public File getTempCacheWavFileName() {
                return null;
            }

            @Override
            public File getTempAmrFileName() {
                return null;
            }

            @Override
            public File getTempMp3FileName() {
                return null;
            }

            @Override
            public File getTempAACFileName() {
                return null;
            }

            @Override
            public File getTempCachePcmFileName() {
                return null;
            }

            @Override
            public File getCachePath() {
                return null;//存储目录可以自定义逻辑，我这里是磁盘的某个文件夹
            }

            @Override
            public String productFileName(String postfix) {
                return null;//这里是控制文件名生成格式 某些服务器端比较变态让你们这边修改
            }
        });

        if(TextUtils.isEmpty(getIntent().getStringExtra("key_history_time"))){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            dreamTime=df.format(new Date());
        }
        else{
            dreamTime=getIntent().getStringExtra("key_history_time");
        }
        tv_title.setText(dreamTime);
    }

    private void initDialoigViews() {
        radio_btn = (CheckBox) notice_confirm_view.findViewById(R.id.radio_btn);
        radio_btn_anonymous = (CheckBox) notice_confirm_view.findViewById(R.id.radio_btn_anonymous);
        radio_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    KeyCounterAction action = new KeyCounterAction();
                    action.setKey("1e77ce970ba04ff9aac4513e67830d9d");
                    EventBus.getDefault().post(action);
                    radio_btn_anonymous.setEnabled(true);
                    radio_btn_anonymous.setTextColor(Color.parseColor("#201f20"));
                } else {
                    KeyCounterAction action = new KeyCounterAction();
                    action.setKey("e6a291310f294351939e65d2e4a3fe12");
                    EventBus.getDefault().post(action);
                    radio_btn_anonymous.setEnabled(false);
                    radio_btn_anonymous.setChecked(false);
                    radio_btn_anonymous.setTextColor(Color.parseColor("#58626e"));
                }
            }
        });
        tv_publish_cancel = (TextView) notice_confirm_view.findViewById(R.id.tv_publish_cancel);
        tv_publish_confirm = (TextView) notice_confirm_view.findViewById(R.id.tv_publish_confirm);
        tv_publish_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notice_confirm_dialog.dismiss();
            }
        });
        tv_publish_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordMyDream();
            }
        });
    }

    private void initBindDialog() {
        notice_confirm_dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = notice_confirm_dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        notice_confirm_dialog.setCancelable(false);
        notice_confirm_dialog.setContentView(notice_confirm_view);
    }


    private void showRecordAudioAnimation() {
        final int audio_size = audio_entities.size();
        float float_percent = audio_size * 1f;
        ValueAnimator audioAnimation = ValueAnimator.ofFloat(0f, float_percent).setDuration((long) (1800 * float_percent));
        audioAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                if ((percent >= 0) && (percent <= 2f)) {
//                    layout_voice_wma_first.setX(edt_dream_desc.getX() + DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 100));
                    tv_length_audio1.setText(((int) (audio_entities.get(0).getLength())) + "'");
                    layout_voice_wma_first.setY((imv_voice.getY() - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 80)));
                    layout_voice_wma_first.setVisibility(View.VISIBLE);
                    if (percent <= 1) {
                        int y = (int) ((imv_voice.getY() - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 80)) * percent);
                        Logger.i(y + "");
//                        layout_voice_wma_first.requestLayout();

                        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(layout_voice_wma_first.getLayoutParams());
                        layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                        int min_width = DisplayUtil.dip2px(App.GetInstance(), 128);
                        int max_width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(App.GetInstance(), 30);
                        int width = min_width + ((int) (audio_entities.get(0).getLength() * (max_width - min_width) / 180));
                        layout_voice_wma_first.getLayoutParams().width = (int) (width * (percent));
                        layout_voice_wma_first.requestLayout();

                    }
                    tv_complete.setEnabled(true);
                    tv_complete.setTextColor(Color.parseColor("#ffffff"));
                }
            }
        });
        audioAnimation.start();
    }

    @Override
    protected void onDestroy() {
        player.stop();
        player.reset();
        player.release();
        player = null;
        super.onDestroy();
    }

    private void recordFinished() {
        edt_dream_desc.setVisibility(View.VISIBLE);
        layout_stop_record_voice.setVisibility(View.GONE);
        ValueAnimator upAnimation_desc = ValueAnimator.ofFloat(0, 1).setDuration(800);
        final float start_y = DisplayUtil.GetDisplayHeight() / 2 - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 100);
        final float end_y = DisplayUtil.dip2px(RecordDreamTitleActivcity.this, -300);
        upAnimation_desc.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
//                layout_center_title.setY(start_y - (start_y - end_y) * percent);
                edt_dream_desc.setY((DisplayUtil.GetDisplayHeight() * 0.25f) * percent);
                if (percent > 0.6) {
                    imv_voice.setVisibility(View.VISIBLE);
                    imv_voice.setAlpha(percent);
                    imv_voice.setY(DisplayUtil.GetDisplayHeight() - (DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 85) * percent));
                }
            }
        });
        upAnimation_desc.start();
    }

    @Override
    public void setupData() {
        animation_good_dreams = ValueAnimator.ofFloat(DisplayUtil.GetDisplayHeight() + 300, DisplayUtil.GetDisplayHeight() / 2 - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 100)).setDuration(800);
        animation_good_dreams.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                layout_center_title.setY(percent);
            }
        });
        animation_good_dreams.start();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                is_audio1_pause = false;
                imv_playing_status_audio1.setImageResource(R.mipmap.audio_pause);
            }
        });
        model = new DreamModelImpl();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void showDreamDesc() {
        edt_dream_desc.setVisibility(View.VISIBLE);
        ValueAnimator upAnimation_desc = ValueAnimator.ofFloat(0, 1).setDuration(800);
        final float start_y = DisplayUtil.GetDisplayHeight() / 2 - DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 100);
        final float end_y = DisplayUtil.dip2px(RecordDreamTitleActivcity.this, -300);
        upAnimation_desc.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                layout_center_title.setY(start_y - (start_y - end_y) * percent);
                edt_dream_desc.setY(DisplayUtil.GetDisplayHeight() - (DisplayUtil.GetDisplayHeight() * 0.75f) * percent);
                if (percent > 0.6) {
                    imv_voice.setVisibility(View.VISIBLE);
                    imv_voice.setY(DisplayUtil.GetDisplayHeight() - (DisplayUtil.dip2px(RecordDreamTitleActivcity.this, 85) * percent));
                }
            }
        });
        upAnimation_desc.start();
    }


    public RecordManagerI getRecordManager() {
        if (recordManager == null) {
            switch (mediaType) {
                case AAC:
                    recordManager = RecordFactory.getAAcRocrdInstance();
                    break;
                case WAV:
                    recordManager = RecordFactory.getWavRecordInstance();
                    break;
                case MP3:
                    recordManager = RecordFactory.getMp3RecordInstance();
                    break;
                case WAV_TO_MP3:
                    recordManager = RecordFactory.getWavRecordMp3OutInstance();
                    break;
                case AMR:
                    recordManager = RecordFactory.getAmrRocrdInstance();
                    break;
            }
            recordManager.setOnTimeSecondChanage(new RecordManagerI.OnTimeSecondChanage() {
                @Override
                public void onSecondChnage(int duration) {
                    int second = duration / 1000;
                    String textTime = generateTime(duration);
                    Logger.i("录制的时常秒:" + second);
                    audio_entities.get(audio_entities.size() - 1).setLength((int) duration);
                }
            });
            recordManager.setOnTimeOutStopListener(new RecordManagerI.OnTimeOutStopListener() {
                @Override
                public void onStop() {
                    if (audio_entities.size() >= 1) {
                        mAudioFile = recordManager.getFile();
                        File tempCacheMp3FileName = MediaDirectoryUtils.getTempMp3FileName();
                        audio_entities.get(audio_entities.size() - 1).setAudioPath(mAudioFile.getAbsolutePath());
                        showRecordAudioAnimation();
                        try {
                            tempCacheMp3FileName.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        return recordManager;
    }


    /**
     * 精确到毫秒  不是时间戳  new Date().getTime()-new Date().getTime()的时间 比如。
     *
     * @param position
     * @return
     */
    public static String generateTime(long position) {
        if (position <= 0) {
            return "00:00";
        }
        int totalSeconds = (int) (position / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }

    private void showRecordVoice() {
        edt_dream_desc.setVisibility(View.GONE);
        ValueAnimator alphaAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500);
        alphaAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                imv_voice.setAlpha(1 - percent);
                layout_stop_record_voice.setVisibility(View.VISIBLE);
                imv_stop_record_voice.setScaleX(percent);
                imv_stop_record_voice.setScaleY(percent);
                if (percent == 1) {
                    imv_bg_stop_record_voice.setVisibility(View.VISIBLE);
                    imv_bg_stop_record_voice_front.setVisibility(View.VISIBLE);
                }
            }
        });
        alphaAnimation.start();
        if (getRecordManager().isRecordIng()) {//在录制中
            if (getRecordManager().getCurrenttime() < 2) {//小于5秒不鸟
                Toast.makeText(this, "录音时间太短", Toast.LENGTH_SHORT).show();
            } else {
                getRecordManager().stopRecord();//否则停止
            }
        } else {//不再录制中 开始新的录制
            try {
                getRecordManager().startRecordCreateFile(60);
            } catch (IOException e) {
                getRecordManager().stopRecord();
                e.printStackTrace();
                Toast.makeText(this, "无法录制 " + e.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @OnClick({R.id.imv_good_dreams, R.id.imv_bad_dreams, R.id.imv_normal_dreams, R.id.layout_back, R.id.imv_voice, R.id.imv_stop_record_voice, R.id.imv_playing_status_audio1, R.id.imv_playing_status_audio2, R.id.imv_playing_status_audio3, R.id.tv_complete})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.imv_good_dreams:
                imv_good_dreams.setScaleX(1.2f);
                imv_good_dreams.setScaleY(1.2f);
                imv_bad_dreams.setScaleX(1f);
                imv_bad_dreams.setScaleY(1f);
                imv_normal_dreams.setScaleX(1f);
                imv_normal_dreams.setScaleY(1f);
                dream_type = 1;
                KeyCounterUtils.SendKeyCounter("bd3e354c7e1d445794fe31089001021c");
                showDreamDesc();
                break;
            case R.id.imv_bad_dreams:
                KeyCounterUtils.SendKeyCounter("6dfd763720474faf9fa22e3049244fd8");
                imv_bad_dreams.setScaleX(1.2f);
                imv_bad_dreams.setScaleY(1.2f);
                imv_good_dreams.setScaleX(1f);
                imv_good_dreams.setScaleY(1f);
                imv_normal_dreams.setScaleX(1f);
                imv_normal_dreams.setScaleY(1f);
                dream_type = 2;
                showDreamDesc();
                break;
            case R.id.imv_normal_dreams:
                KeyCounterUtils.SendKeyCounter("cdd39cfdd14d4c51ae3b13f5d82aa59b");
                imv_normal_dreams.setScaleX(1.2f);
                imv_normal_dreams.setScaleY(1.2f);
                imv_good_dreams.setScaleX(1f);
                imv_good_dreams.setScaleY(1f);
                imv_bad_dreams.setScaleX(1f);
                imv_bad_dreams.setScaleY(1f);
                dream_type = 0;
                showDreamDesc();
                break;
            case R.id.imv_voice:
                //只需要记录一段语音 start
                audio_entities.clear();
                layout_voice_wma_first.setVisibility(View.GONE);
                layout_voice_wma_second.setVisibility(View.GONE);
                layout_voice_wma_third.setVisibility(View.GONE);
                tv_complete.setEnabled(false);
                tv_complete.setTextColor(Color.parseColor("#58626e"));
                wave_animator.start();
                RecordAudioEntity audioEntity = new RecordAudioEntity();
                audio_entities.add(audioEntity);
                showRecordVoice();
                //只需要记录一段语音 end
                break;
            case R.id.imv_stop_record_voice:
//                audioRecorder.stopRecord();
                getRecordManager().stopRecord();
                wave_animator.cancel();
                layout_voice_wma_first.getLayoutParams().width = 0;
                layout_voice_wma_second.getLayoutParams().width = 0;
                layout_voice_wma_third.getLayoutParams().width = 0;
                recordFinished();
                break;
            case R.id.imv_playing_status_audio1:
                if (is_audio1_pause) {
                    player.start();
                    is_audio1_pause = false;
                    imv_playing_status_audio1.setImageResource(R.mipmap.audio_playing);
                } else {
                    if (player.isPlaying()) {
                        player.pause();
                        is_audio1_pause = true;
                        imv_playing_status_audio1.setImageResource(R.mipmap.audio_pause);
                    } else {
                        is_audio1_pause = false;
                        player.reset();
//                imv_playing_status_audio1.setImageResource(R.mipmap.audio_playing);
//                imv_playing_status_audio2.setImageResource(R.mipmap.audio_pause_stop);
//                imv_playing_status_audio3.setImageResource(R.mipmap.audio_pause_stop);
                        try {
                            imv_playing_status_audio1.setImageResource(R.mipmap.audio_playing);
                            player.setDataSource(audio_entities.get(0).getAudioPath());
                            player.prepare();
                            player.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case R.id.imv_playing_status_audio2:
                player.reset();
//                imv_playing_status_audio1.setImageResource(R.mipmap.audio_pause_stop);
//                imv_playing_status_audio2.setImageResource(R.mipmap.audio_playing);
//                imv_playing_status_audio3.setImageResource(R.mipmap.audio_pause_stop);
                try {
                    player.setDataSource(audio_entities.get(1).getAudioPath());
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.imv_playing_status_audio3:
                player.reset();
//                imv_playing_status_audio1.setImageResource(R.mipmap.audio_pause_stop);
//                imv_playing_status_audio2.setImageResource(R.mipmap.audio_pause_stop);
//                imv_playing_status_audio3.setImageResource(R.mipmap.audio_playing);
                try {
                    player.setDataSource(audio_entities.get(2).getAudioPath());
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.layout_back:
                App.GetInstance().finishActivity(this);
                break;
            case R.id.tv_complete:
                radio_btn.setChecked(true);
                notice_confirm_dialog.show();
                edt_dream_desc.setText(edt_dream_desc.getText().toString().trim());
                break;
        }
    }

    @Override
    protected void onStop() {
        getRecordManager().stopRecord();
        super.onStop();
    }

    private void recordMyDream() {
        String dreamStatus = "normal";
        if (radio_btn.isChecked()) {
            dreamStatus = "public";
        } else {
            dreamStatus = "normal";
        }
        String showName="y";
        if(radio_btn_anonymous.isChecked()){
            showName="n";
        }
        else{
            showName="y";
        }
        RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
        Map<String, RequestBody> params = null;
        if (audio_entities.size() == 0) {
            params = RetrofitUploadFileParameterBuilder.newBuilder()
                    .addParameter("token", PreferenceUtils.GetUserToken())
                    .addParameter("userId", PreferenceUtils.GetUserId())
                    .addParameter("dreamType", dream_type + "")
                    .addParameter("task", "saveDreamRecord")
                    .addParameter("dreamStatus", dreamStatus)
                    .addParameter("dreamText", edt_dream_desc.getText().toString().trim())
                    .addParameter("showName",showName)
                    .addParameter("dreamTime",dreamTime)
                    .bulider();
        } else {
            File voice_file = new File(audio_entities.get(0).getAudioPath());
            params = RetrofitUploadFileParameterBuilder.newBuilder()
                    .addParameter("token", PreferenceUtils.GetUserToken())
                    .addParameter("userId", PreferenceUtils.GetUserId())
                    .addParameter("dreamType", dream_type + "")
                    .addParameter("dreamText", edt_dream_desc.getText().toString())
                    .addParameter("task", "saveDreamRecord")
                    .addParameter("dreamStatus", dreamStatus)
                    .addParameter("file", voice_file)
                    .addParameter("showName",showName)
                    .addParameter("dreamTime",dreamTime)
                    .bulider();
        }
        model.RecordDream(params).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                if (audio_entities.size() > 0) {
                    File voice_file = new File(audio_entities.get(0).getAudioPath());
                    if (voice_file.exists()) {
                        voice_file.delete();
                    }
                }
                if (notice_confirm_dialog != null && notice_confirm_dialog.isShowing()) {
                    notice_confirm_dialog.dismiss();
                }
                if(radio_btn.isChecked()&&!radio_btn_anonymous.isChecked()){
                    ToastUtils.showShortToast(RecordDreamTitleActivcity.this, "发布成功");
                }
                if(radio_btn.isChecked()&&radio_btn_anonymous.isChecked()){
                    ToastUtils.showShortToast(RecordDreamTitleActivcity.this, "匿名发布成功");
                }
                if(!radio_btn.isChecked()&&!radio_btn_anonymous.isChecked()){
                    ToastUtils.showShortToast(RecordDreamTitleActivcity.this, "保存本地成功");
                }
                App.GetInstance().finishActivity(RecordDreamTitleActivcity.this);
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                if (audio_entities.size() > 0) {
                    File voice_file = new File(audio_entities.get(0).getAudioPath());
                    if (voice_file.exists()) {
                        voice_file.delete();
                    }
                }
                ToastUtils.showShortToast(RecordDreamTitleActivcity.this, response.getDesc());
            }
        });
    }
}
